package org.xdj.blue.java.aio.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AysnSocketServer implements Runnable {
	
	public static Logger logger = LoggerFactory.getLogger(AysnSocketServer.class);
	
	private int port;
	CountDownLatch latch;
	AsynchronousServerSocketChannel asynServerSocketChannel;
	
	public  AysnSocketServer(int port){
		this.port = port;
		try {
			asynServerSocketChannel = AsynchronousServerSocketChannel.open();
			asynServerSocketChannel.bind(new InetSocketAddress(port));
			logger.debug("--监听服务启动--"+"port:"+port+"--");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void run() {
		System.out.println("--AysnSocketServer线程名："+Thread.currentThread().getName()+"--");
		latch = new CountDownLatch(1);
		doAccept();
		try {
			latch.await();
			System.out.println("--latch.await--");
		} catch (InterruptedException e) {
			System.out.println("--error:"+"latch.wait---");
			e.printStackTrace();
		}
	}
	private void doAccept(){
		asynServerSocketChannel.accept(this, new AcceptCompletionHandler());
	}

}
